package com.zzyl.nursing.service.impl;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住管理信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IContractService contractService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Autowired
    private IBedService bedService;

    /**
     * 查询入住管理信息
     *
     * @param id 入住管理信息主键
     * @return 入住管理信息
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住管理信息列表
     *
     * @param checkIn 入住管理信息
     * @return 入住管理信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住管理信息
     *
     * @param checkIn 入住管理信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住管理信息
     *
     * @param checkIn 入住管理信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住管理信息
     *
     * @param ids 需要删除的入住管理信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住管理信息信息
     *
     * @param id 入住管理信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param checkInDataDto
     * @return
     */
    @Override
    @Transactional
    public int apply(CheckInDataDto checkInDataDto) {
        //获取老人对象
        CheckInElderDto elderDto = checkInDataDto.getCheckInElderDto();
        //获取合同对象
        CheckInContractDto contractDto = checkInDataDto.getCheckInContractDto();
        //获取入住基本配置对象
        CheckInConfigDto checkIn = checkInDataDto.getCheckInConfigDto();
        //获取老人的家庭对象
        List<ElderFamilyDto> elderFamilies = checkInDataDto.getElderFamilyDtoList();
        //查询床位信息
        Bed bed = this.bedService.getById(checkIn.getBedId());

        //1.判断老人是否已经入住了
        //获取老人的身份证号码
        String idCardNo = elderDto.getIdCardNo();
        Elder elder = this.elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, idCardNo)
                .eq(Elder::getStatus, 1)
                .one();
        if (ObjectUtil.isNotNull(elder)) {
            //不为空则已经入住过了
            throw new BaseException("你已经入住了哦,亲~~");
        }
        //2.为空代表老人并没有入住，所以可以添加到数据库中
        elder = insert0rUpdateElder(idCardNo, elderDto, bed);

        //3.新增入住基本信息
        CheckIn check = insertCheckIn(elder, checkIn, bed, elderFamilies);

        //4.新增入住配置信息
        CheckInConfig config = insertCheckInConfig(checkIn, check);

        //5.新增合同信息
        int i = insertContract(contractDto, check, elder);

        return i;
    }

    /**
     * 查看入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDataVO detail(Long id) {
        //1.查询老人入住配置信息
        CheckIn check = this.getById(id);
        CheckInConfig config = this.checkInConfigService.lambdaQuery()
                .eq(CheckInConfig::getCheckInId, check.getId())
                .one();
        CheckInConfigVO configVO = new CheckInConfigVO();
        BeanUtils.copyProperties(config, configVO);
        configVO.setEndDate(check.getEndDate());
        configVO.setStartDate(check.getStartDate());
        configVO.setBedNumber(check.getBedNumber());
        //2.查询老头基本信息
        Elder elder = this.elderService.getById(check.getElderId());
        CheckInElderVO elderVO = new CheckInElderVO();
        //计算年龄
        long age = getAge(elder);
        elderVO.setAge((int) age);
        BeanUtils.copyProperties(elder, elderVO);
        //3.查询老人的家属详细信息
        List<ElderFamilyVOList> elderFamilyVos = JSON.parseArray(check.getRemark(), ElderFamilyVOList.class);
        //4.查询合同信息
        Contract contract = this.contractService.lambdaQuery()
                .eq(Contract::getElderId, elder.getId())
                .one();
        CheckInContractVO contractVO = new CheckInContractVO();
        BeanUtils.copyProperties(contract, contractVO);
        contractVO.setElderId(elder.getId());
        CheckInDataVO dataVO = new CheckInDataVO();
        dataVO.setCheckInConfigVo(configVO);
        dataVO.setContract(contractVO);
        dataVO.setElderFamilyVoList(elderFamilyVos);
        dataVO.setCheckInElderVo(elderVO);
        return dataVO;
    }

    /**
     * 计算年龄
     *
     * @param elder
     * @return
     */
    private static long getAge(Elder elder) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String birthday = elder.getBirthday();
        LocalDate endTime = LocalDate.parse(birthday, formatter);
        LocalDate now = LocalDate.now();
        return ChronoUnit.YEARS.between(endTime, now);
    }

    /**
     * 新增合同
     *
     * @param contractDto
     * @param check
     * @param elder
     * @return
     */
    private int insertContract(CheckInContractDto contractDto, CheckIn check, Elder elder) {
        try {
            Contract contract = new Contract();
            BeanUtils.copyProperties(contractDto, contract);
            contract.setElderId(Math.toIntExact(elder.getId()));
            contract.setStartDate(check.getEndDate());
            contract.setEndDate(check.getEndDate());
            contract.setContractNumber(contractDto.getContractName());
            contract.setElderName(elder.getName());
            String str = IdWorker.getIdStr();
            contract.setContractNumber(str);
            this.contractService.save(contract);
            return 1;
        } catch (BeansException e) {
            throw new BaseException("请核查信息");
        }
    }

    /**
     * 新增入住配置信息
     *
     * @param checkIn
     * @param check
     */
    private CheckInConfig insertCheckInConfig(CheckInConfigDto checkIn, CheckIn check) {
        CheckInConfig config = new CheckInConfig();
        BeanUtils.copyProperties(checkIn, config);
        config.setCheckInId(check.getId());
        this.checkInConfigService.save(config);
        return config;
    }

    /**
     * 新增或者修改老人的基本信息
     *
     * @param idCardNo
     * @param elderDto
     * @param bed
     * @return
     */
    private Elder insert0rUpdateElder(String idCardNo, CheckInElderDto elderDto, Bed bed) {
        Elder elder = new Elder();
        //判断老人是否曾经入住了
        Elder elderEr = this.elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, idCardNo)
                .ne(Elder::getStatus, 0)
                .one();
        BeanUtils.copyProperties(elderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        if (ObjectUtil.isNotNull(elderEr)) {
            //如果不为空，则代表老人曾经入住过,则进行修改老人的基本信息
            this.elderService.updateById(elder);
        } else {
            // 如果为空则代表老人是第一次入住，所以为新增
            this.elderService.save(elder);
        }
        return elder;
    }

    /**
     * 新增入住基本信息
     *
     * @param elder
     * @param checkIn
     * @param bed
     * @return
     */
    private CheckIn insertCheckIn(Elder elder, CheckInConfigDto checkIn, Bed bed, List<ElderFamilyDto> elderFamilies) {
        CheckIn check = new CheckIn();
        check.setElderName(elder.getName());
        check.setElderId(elder.getId());
        check.setIdCardNo(elder.getIdCardNo());
        check.setStartDate(checkIn.getStartDate());
        check.setEndDate(checkIn.getEndDate());
        check.setNursingLevelName(checkIn.getNursingLevelName());
        check.setBedNumber(bed.getBedNumber());
        check.setRemark(JSON.toJSONString(elderFamilies));
        this.save(check);
        return check;
    }
}
